{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "开始线程：线程——1\n",
      "开始线程：线程--2\n",
      "结束线程：线程——1\n",
      "结束线程：线程--2\n"
     ]
    }
   ],
   "source": [
    "# 方法一：继承Thread类\n",
    "import threading\n",
    "import time\n",
    "class MyThread(threading.Thread):\n",
    "    def __init__(self,thread_id,name):\n",
    "        super().__init__()\n",
    "        self.thread_id = thread_id\n",
    "        self.name = name\n",
    "    def run(self):\n",
    "        print(f'开始线程：{self.name}')\n",
    "        time.sleep(2)\n",
    "        print(f'结束线程：{self.name}')\n",
    "# 创建线程类\n",
    "thread1 = MyThread(1,'线程——1')\n",
    "thread2 = MyThread(2,'线程--2')\n",
    "\n",
    "# 开始线程\n",
    "\n",
    "thread1.start()\n",
    "thread2.start()\n",
    "\n",
    "# 主线程等待子线程结束\n",
    "thread1.join()\n",
    "thread2.join()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "开始线程：线程1\n",
      "开始线程：线程2\n",
      "结束线程：线程1\n",
      "结束线程：线程2\n"
     ]
    }
   ],
   "source": [
    "# 使用threading.Thread直接创建\n",
    "import threading\n",
    "import time\n",
    "def thread_fucntion(name):\n",
    "    print(\"开始线程：{}\".format(name))\n",
    "    time.sleep(2)\n",
    "    print(\"结束线程：{}\".format(name))\n",
    "# 直接使用 threading 创建线程\n",
    "thread1 = threading.Thread(target=thread_fucntion,args=(\"线程1\",))\n",
    "thread2 = threading.Thread(target=thread_fucntion,args=(\"线程2\",))\n",
    "\n",
    "thread1.start()\n",
    "thread2.start()\n",
    "\n",
    "thread1.join()\n",
    "thread2.join()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
